﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using eTMS.Controllers.GiaoVienService;
using eTMS.Controllers;
using eTMS.Commons;
using eTMS.Controllers.BoMonService;
using eTMS.Controllers.MonHocService;
namespace eTMS.Forms.ManageList
{
    public partial class FrmGiaoVien : eTMS.Controls.BaseForm
    {
        public FrmGiaoVien()
        {
            InitializeComponent();
        }
        #region Variables
        private GiaoVienController controller = new GiaoVienController();
        #endregion
        #region Screen Functions
        //Load All lable text
        private void LoadLanguage()
        {
            this.Text = GiaoVienStringMapping.GiaoVien;
            this.labelFormTitle.Text = Constants.APP_ADMINISTRATION + " " + GiaoVienStringMapping.GiaoVien;
            this.groupBoxDetail.Text = Constants.APP_DETAIL;
            this.groupBoxList.Text = Constants.APP_LIST;
            this.ColumnSTT.HeaderText = Constants.APP_INDEX;
            labelMaGiaoVien.Text = GiaoVienStringMapping.MaGiaoVien;
            ColumnMaGiaoVien.HeaderText = GiaoVienStringMapping.MaGiaoVien;
            labelHoTenGiaoVien.Text = GiaoVienStringMapping.HoTenGiaoVien;
            ColumnHoTenGiaoVien.HeaderText = GiaoVienStringMapping.HoTenGiaoVien;
            labelNgaySinh.Text = GiaoVienStringMapping.NgaySinh;
            ColumnNgaySinh.HeaderText = GiaoVienStringMapping.NgaySinh;
            labelDiaChi.Text = GiaoVienStringMapping.DiaChi;
            labelEmail.Text = GiaoVienStringMapping.Email;
            labelDienThoai.Text = GiaoVienStringMapping.DienThoai;
            labelGioiTinh.Text = GiaoVienStringMapping.GioiTinh;
            //Search
            this.groupBoxFilter.Text = Constants.APP_SEARCH;
            labelMaGiaoVienFilter.Text = GiaoVienStringMapping.MaGiaoVien;
            cbkHoTenGiaoVienFilterExact.Text = Constants.APP_SEARCH_EXACT;
            labelHoTenGiaoVienFilter.Text = GiaoVienStringMapping.HoTenGiaoVien;
            //end
        }
        //Get entity selected from datagrid
        private GiaoVienEntity GetObject()
        {
            GiaoVienEntity o = controller.MapDataRowToObject(((DataRowView)gridData.SelectedRows[0].DataBoundItem).Row);
            return o;
        }
        //Get entites selected from datagrid
        private List<DataRow> GetSelectedDataRows()
        {
            List<DataRow> ls = new List<DataRow>();
            for (int i = 0; i < gridData.SelectedRows.Count; i++)
            {
                ls.Add(GetDataRow(gridData.SelectedRows[i].Index));
            }
            return ls;
        }
        //Get the selected data row in datagrid
        private DataRow GetSelectedDataRow()
        {
            DataRow row = GetDataRow(gridData.SelectedRows[0].Index);
            return row;
        }
        //Get the selected data row in datagrid
        private DataRow GetDataRow(int index)
        {
            DataRow row = ((DataRowView)gridData.Rows[index].DataBoundItem).Row;
            return row;
        }
        //Reset all textbox
        private void ClearScreen()
        {
            txtMaGiaoVien.Text = "";
            txtHoTenGiaoVien.Text = "";
            txtNgaySinh.Text = "";
            txtDiaChi.Text = "";
            errorProviderData.Clear();
        }
        //Lock-Unlock control in screen
        private void LockScreen(bool IsLocked)
        {
            ucCommand.LockControl(IsLocked);
            txtMaGiaoVien.ReadOnly = IsLocked;
            txtHoTenGiaoVien.ReadOnly = IsLocked;
            txtNgaySinh.ReadOnly = IsLocked;
            txtDiaChi.ReadOnly = IsLocked;
            txtEmail.ReadOnly = IsLocked;
            txtDienThoai.ReadOnly = IsLocked;
            txtGioiTinh.ReadOnly = IsLocked;
            btnAddMonHoc.Enabled = !IsLocked;
            btnRemoveMonHoc.Enabled = !IsLocked;
            btnSearch.Enabled = IsLocked;
            treeKhoaBoMonMonHocLopTinChi1.Enabled = IsLocked;
            gridMonHoc.ReadOnly = IsLocked;
            ColCheckMon.Visible = !IsLocked;
        }
        //Copy data from control in screen to object
        private void CopyFromSreen(GiaoVienEntity o)
        {
            o.MaGiaoVien = Convert.ToString(txtMaGiaoVien.Text);
            o.HoTenGiaoVien = Convert.ToString(txtHoTenGiaoVien.Text);
            o.NgaySinh = Convert.ToString(txtNgaySinh.Text);
            o.DiaChi = Convert.ToString(txtDiaChi.Text);
            o.BoMon_ID = treeKhoaBoMonMonHocLopTinChi1.GetListSelectedBoMon()[0];
            o.Email = txtEmail.Text.Trim();
            o.DienThoai = txtDienThoai.Text.Trim();
            o.GioiTinh = controller.ConvertByte(txtGioiTinh.SelectedValue);

        }
        //Bind data from object to control in screen
        private void CopyToSreen(GiaoVienEntity o)
        {
            if (!o.IsNullMaGiaoVien)
            {
                txtMaGiaoVien.Text = Convert.ToString(o.MaGiaoVien);
            }
            if (!o.IsNullHoTenGiaoVien)
            {
                txtHoTenGiaoVien.Text = Convert.ToString(o.HoTenGiaoVien);
            }
            if (!o.IsNullNgaySinh)
            {
                txtNgaySinh.Text = Convert.ToString(o.NgaySinh);
            }
            if (!o.IsNullDiaChi)
            {
                txtDiaChi.Text = Convert.ToString(o.DiaChi);
            }
            txtGioiTinh.SelectedValue = o.GioiTinh;
            txtDienThoai.Text = o.DienThoai;
            txtEmail.Text = o.Email;
        }
        //Validate all data from control in screen before Save data
        protected bool ValidateScreen()
        {
            bool result = true;
            if ((treeKhoaBoMonMonHocLopTinChi1.GetListSelectedBoMon().Count <= 0))
            {
                treeKhoaBoMonMonHocLopTinChi1.Focus();
                errorProviderData.SetError(treeKhoaBoMonMonHocLopTinChi1, Constants.MSS_ERROR_DROPDOWN);
                result = false;
            }
            else
            {
                errorProviderData.SetError(treeKhoaBoMonMonHocLopTinChi1, "");
            }
            if (!result)
            {
                ShowInfo(Constants.MSS_REQUIRE_FIELD);
            }
            if (result)
            {
                //Check if exists MaGiaoVien				
                bool existsMaGiaoVien = controller.CheckExistsMaGiaoVien(txtMaGiaoVien.Text);
                bool editexists = false;
                if (Flag == ACTIONENUM.Edit)
                {
                    DataRow row = GetSelectedDataRow();
                    string newVal = txtMaGiaoVien.Text;
                    editexists = Convert.ToString(row["MaGiaoVien"]) != Convert.ToString(newVal);
                }
                if (existsMaGiaoVien && ((Flag == ACTIONENUM.AddNew) || editexists))
                {
                    result = false;
                    errorProviderData.SetError(txtMaGiaoVien, Constants.MSS_ERROR_DATA_UNIQUE);
                    txtMaGiaoVien.Focus();
                    ShowInfo(Constants.MSS_ERROR_EXISTS_DATA);
                }
                else
                {
                    errorProviderData.SetError(txtMaGiaoVien, "");
                }
            }
            return result;
        }
        //Copy data from selected object to control in screen
        private void BindInfo()
        {
            if (gridData.SelectedRows.Count == 0) return;
            if (gridData.SelectedRows[0].Index < gridData.Rows.Count)
            {
                GiaoVienEntity o = GetObject();
                controller.GiaoVienObject = o;
                CopyToSreen(o);
                BindMonHoc();
            }
        }
        #endregion
        #region Business
        //AddNew data to database
        private bool AddNewData()
        {
            bool rval = false;
            controller.ResetObject();
            CopyFromSreen(controller.GiaoVienObject);
            rval = controller.AddNew();
            if (rval)
            {

                controller.SaveChiTiet();
                DataRow row = controller.Table.NewRow();
                row["STT"] = controller.Table.Rows.Count + 1;
                controller.MapObjectToDataRow(row);
                controller.Table.Rows.Add(row);
                gridData.DataSource = null;
                gridData.DataSource = controller.Table;
            }
            return rval;
        }
        //Update data to database
        private bool UpdateData()
        {
            DataRow row = GetSelectedDataRow();
            controller.LoadObject((Int32)row["GiaoVien_ID"]);
            CopyFromSreen(controller.GiaoVienObject);
            bool rval = controller.Update();
            if (rval)
            {
                controller.SaveChiTiet();
                controller.MapObjectToDataRow(row);
                gridData.InvalidateRow(gridData.SelectedRows[0].Index);
            }
            return rval;
        }
        //Delete data from database
        private bool DeleteData()
        {
            List<DataRow> ls = GetSelectedDataRows();
            if (ls.Count == 0) return false;
            bool rval = true;
            try
            {
                gridData.DataSource = null;
                foreach (DataRow row in ls)
                {
                    if (controller.DeleteByID((Int32)row["GiaoVien_ID"]))
                    {
                        this.controller.Table.Rows.Remove(row);
                    }
                    else
                    {
                        rval = false;
                    }
                }
                this.controller.ResetTableIndex();
                gridData.DataSource = this.controller.Table;
            }
            catch
            {
                return false;
            }
            return true;
        }
        #endregion
        #region DataBinding
        //Bind data to datagrid
        private void LoadData()
        {
            gridData.ClearSelection();
            gridData.AutoGenerateColumns = false;
            controller.LoadAllDSGiaoVien(false);
            controller.Table.DefaultView.RowFilter = GetFilter();
            gridData.DataSource = controller.Table;
            gridData.AutoResizeColumns();
            if (gridData.Rows.Count > 0)
                gridData.Rows[0].Selected = true;
        }
        #endregion
        #region Windows Control EventHandlers
        private void FrmGiaoVien_Load(object sender, EventArgs e)
        {
            txtGioiTinh.BindData();
            ucCommand.SetImportVisible(true);
            ucCommand.ResetAllPos();
            LoadLanguage();
            LoadData();
            LockScreen(true);
        }
        private void gridData_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            BindInfo();
        }
        private void ucCommand_OnAddNew(object sender, EventArgs e)
        {
            List<int> lsBoMonID = treeKhoaBoMonMonHocLopTinChi1.GetListSelectedBoMon();
            if (lsBoMonID.Count != 1)
            {
                ShowWarning("Bạn phải chọn một bộ môn cho giáo viên!");
                return;
            }
            ClearScreen();
            LockScreen(false);
            Flag = ACTIONENUM.AddNew;
            txtMaGiaoVien.Focus();
            controller.ResetObject();
            controller.LoadChiTiet(0);
            gridMonHoc.AutoGenerateColumns = false;
            gridMonHoc.DataSource = controller.TableChiTiet;
        }
        private void ucCommand_OnDelete(object sender, EventArgs e)
        {
            if (gridData.SelectedRows.Count == 0)
            {
                ShowInfo(Constants.MSS_CHOOSERECORD_REQUIRE);
                return;
            }
            if (!Confirm(Constants.MSS_CONFIRM_DELETE)) return;
            DeleteData();
            this.gridData.Focus();
        }
        private void ucCommand_OnEdit(object sender, EventArgs e)
        {
            if (gridData.SelectedRows.Count == 0)
            {
                ShowInfo(Constants.MSS_CHOOSERECORD_REQUIRE);
                return;
            }
            LockScreen(false);
            Flag = ACTIONENUM.Edit;
            txtMaGiaoVien.Focus();
            if (controller.TableChiTiet != null)
            {
                controller.TableChiTiet.DefaultView.RowFilter = "";
            }
        }
        private void ucCommand_OnSave(object sender, EventArgs e)
        {
            if (!ValidateScreen())
                return;
            if (Flag == ACTIONENUM.Edit)
            {
                if (UpdateData())
                {
                    ShowInfo(Constants.MSS_SAVE_SUCCESS);
                }
                else
                {
                    ShowWarning(Constants.MSS_SAVE_FAILE);
                }
                gridData.Focus();
            }
            else
            {
                if (AddNewData())
                {
                    ShowInfo(Constants.MSS_SAVE_SUCCESS);
                }
                else
                {
                    ShowWarning(Constants.MSS_SAVE_FAILE);
                }
            }
            LockScreen(true);
            Flag = ACTIONENUM.None;
        }
        private void ucCommand_OnSkip(object sender, EventArgs e)
        {
            LockScreen(true);
            if (Flag == ACTIONENUM.AddNew)
            {
                ClearScreen();
                ucCommand.SetFocusAddNew();
            }
            else if (Flag == ACTIONENUM.Edit)
            {
                BindInfo();
                this.gridData.Focus();
            }
            Flag = ACTIONENUM.None;
        }
        #endregion
        #region Filters
        private string GetFilter()
        {
            string strFilter = "";
            if (txtMaGiaoVienFilter.Text.Trim() != "")
            {
                strFilter += " AND MaGiaoVien='" + txtMaGiaoVienFilter.Text.Trim() + "'";

            }
            if (txtHoTenGiaoVienFilter.Text.Trim() != "")
            {
                if (cbkHoTenGiaoVienFilterExact.Checked)
                {
                    strFilter += " AND HoTenGiaoVien='" + txtHoTenGiaoVienFilter.Text.Trim() + "'";
                }
                else
                {
                    strFilter += " AND HoTenGiaoVien LIKE '%" + txtHoTenGiaoVienFilter.Text.Trim() + "%'";
                }
            }
            List<int> lsBoMonID = treeKhoaBoMonMonHocLopTinChi1.GetListSelectedBoMon();
            if (lsBoMonID.Count > 0)
            {
                strFilter += " AND BoMon_ID IN(" + string.Join(",", lsBoMonID.ConvertAll<string>(Convert.ToString).ToArray()) + ")";
            }
            if (strFilter.Length > 0)
                strFilter = strFilter.Substring(4);
            return strFilter;
        }
        private void FilterData()
        {
            gridData.ClearSelection();
            controller.LoadAllDSGiaoVien(false);
            controller.Table.DefaultView.RowFilter = GetFilter();
            gridData.AutoGenerateColumns = false;
            gridData.DataSource = controller.Table;
        }
        private void btnSearch_Click(object sender, EventArgs e)
        {
            FilterData();
        }
        #endregion



        private void BindMonHoc()
        {
            gridMonHoc.AutoGenerateColumns = false;
            gridMonHoc.DataSource = null;
            if (controller.GiaoVienObject != null)
            {
                controller.LoadChiTiet(controller.GiaoVienObject.GiaoVien_ID);
                gridMonHoc.AutoGenerateColumns = false;
                gridMonHoc.DataSource = controller.TableChiTiet;

            }
        }

        private void ucCommand_OnImport(object sender, EventArgs e)
        {
            FrmGiaoVienImport frm = new FrmGiaoVienImport();
            frm.ShowDialog();
        }


        private void treeKhoaBoMonMonHocLopTinChi1_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetData(typeof(List<DataRow>)) != null)
            {
                TreeNode targetNode = treeKhoaBoMonMonHocLopTinChi1.GetNodeAt(new Point(e.X, e.Y));
                if ((targetNode != null) || (!(targetNode.Tag is BoMonEntity)))
                {
                    if (Confirm("Bạn thực sự muốn chuyển các giáo viên đã chọn vào bộ môn " + targetNode.Text + " không?"))
                    {
                        List<DataRow> ls = (List<DataRow>)e.Data.GetData(typeof(List<DataRow>));
                        foreach (DataRow row in ls)
                        {
                            controller.LoadObject((Int32)row["GiaoVien_ID"]);
                            controller.GiaoVienObject.BoMon_ID = ((BoMonEntity)targetNode.Tag).BoMon_ID;
                            controller.Update();
                            row["BoMon_ID"] = controller.GiaoVienObject.BoMon_ID;
                        }
                    }
                }
            }
        }

        private void treeKhoaBoMonMonHocLopTinChi1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetData(typeof(List<DataRow>)) != null)
            {
                e.Effect = DragDropEffects.Move;
            }
        }


        private void treeKhoaBoMonMonHocLopTinChi1_DragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetData(typeof(List<DataRow>)) != null)
            {
                e.Effect = DragDropEffects.Move;
            }
        }
        private void gridData_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                List<DataRow> ls = GetSelectedDataRows();
                gridData.DoDragDrop(ls, DragDropEffects.Move);
            }
        }


        private void btnAddMonHoc_Click(object sender, EventArgs e)
        {
            FrmChonMonHoc frm = new FrmChonMonHoc();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                foreach (MonHocEntity oMonHoc in frm.GetListCheckedMonHoc())
                {
                    controller.AddMonHocToChiTiet(oMonHoc);
                }
            }
        }

        private void treeKhoaBoMonMonHocLopTinChi1_OnSelectedChanged(object sender, EventArgs e)
        {

            LoadData();
        }

    }
}
